package com.controls.ws;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;

import com.Utility.WebServiceCommunicator.WebServiceFlag;
import com.events.WebServiceCommunicatorListener;
import com.objects.Contact;
import com.objects.ContactCheck;
import com.objects.CountrySMSCode;
import com.objects.SecurePackageLog;

public class CountryWSControl extends BaseWSControl {
	public CountryWSControl(Context cxt, WebServiceCommunicatorListener lsn) {
		super(cxt, lsn);
	}

	public boolean getCountry(String accessToken) {
		String content = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soap:Body>"
				+ "<GetCountrySMSCodes xmlns=\"https://www.privacydatasolutions.net/\">"
				+ "<Token>"+accessToken+"</Token>"
				+ "</GetCountrySMSCodes>" + "</soap:Body>" + "</soap:Envelope>";

		fetch(WebServiceFlag.GET_COUNTRY, content);
		return true;
	}

	/**
	 * 
	 * @param xml
	 * @return
	 */

	public ArrayList<CountrySMSCode> parseCountry(String xml) {
		ArrayList<CountrySMSCode> items = new ArrayList<CountrySMSCode>();
		Document doc = getDomElement(xml);
		if (doc == null) {
			return items;
		}

		NodeList results = doc
				.getElementsByTagName("GetCountrySMSCodesResult");
		JSONArray mArray = null;
		if (results.getLength() > 0) {
			Node node = results.item(0);
			try {
				mArray = new JSONArray(node.getTextContent());
			} catch (DOMException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (mArray != null) {
			for (int i = 0; i < mArray.length(); i++) {
				try {
					JSONObject obj = mArray.getJSONObject(i);
					CountrySMSCode item = new CountrySMSCode();
					if (obj.has("Country")) {
						item.setTitle(obj.getString("Country"));
					}
					if (obj.has("SMSCode")) {
						item.setCode(obj.getString("SMSCode"));
					}
					
					items.add(item);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return items;
	}

}
